package com.qxzl.filter;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice   //控制器增强
public class ExceptionFilter {
    @ExceptionHandler(value = Exception.class)//异常捕获
    @ResponseBody
    public Object defaultErrorHandler(HttpServletRequest req, Exception e)  {
        e.printStackTrace();
        Map<String, Object> attributes = new HashMap<String, Object>();
//        Json json = new Json();
        if (e instanceof BusinessException) {
            BusinessException e2 = (BusinessException) e;
            attributes.put("success",false);
            attributes.put("code",e2.getCode());
            attributes.put("message",e2.getMsg());
        }else {
            attributes.put("success",false);
            attributes.put("code", "fcerror");
            attributes.put("message",e.getMessage());
        }

        ModelAndView mv = new ModelAndView();
        /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */
        FastJsonJsonView view = new FastJsonJsonView();
        view.setAttributesMap(attributes);
        mv.setView(view);
        return attributes;
    }
}
